package com.zyy.weather.controller;

import com.zyy.weather.dto.XmlDTO;
import com.zyy.weather.entity.TextMessage;
import com.zyy.weather.service.WeixinService;
import com.zyy.weather.util.MessageUtil;
import com.zyy.weather.weixin.AesException;
import com.zyy.weather.weixin.WXBizMsgCrypt;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

@RestController
@Log4j2
public class CheckUrlController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private Environment environment;

    //将此写入配置文件
    private String token = "yR8CQmJoBN1epEo6ioy4Llk3cMuE";
    private String encodingAESKey = "yzDqhK8mbtuG1gLeooLksCN9zogVj3UEPvnkwzrHppP";
    //企业ID
    private String corpId = "ww77f62d9043238de5";

    WXBizMsgCrypt wxcpt = null;

    {
        try {
            wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);

        } catch (AesException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/checkUrl")
    public String checkUrl(HttpServletRequest request) {
        //微信加密签名
        String msgSignature = request.getParameter("msg_signature");
        //解析url上的参数值
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        System.out.println(msgSignature + "==" + timestamp + "==" + nonce + "==" + echostr);
        //需要返回的明文
        String goEchostr = null;
        try {
            goEchostr = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
        } catch (AesException e) {
            log.error("验证url错误，错误原因请查看异常");
            e.printStackTrace();
        }
        return goEchostr;
    }

    String encryptMsg = "";

    @PostMapping("/checkUrl")
    public String decryptMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从request中取值
        //微信加密签名
        String msgSignature = request.getParameter("msg_signature");
        //解析url上的参数值
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        //post请求的密文数据
        //从请求中读取整个post数据
        InputStream inputStream = request.getInputStream();
        String sReqData = IOUtils.toString(inputStream, "UTF-8");
        try {
            //检验消息的真实性，并且获取解密后的明文.
            String sMsg = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, sReqData);
            log.info("接收到的消息是：" + sMsg);
            //处理接收到的数据取出消息内容
            XmlDTO xmlDTO = weixinService.getMessage(sMsg);
            log.info("接收到的内容:" + xmlDTO);

            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(corpId);
            //得到回答语句
            String reply = weixinService.getReply(xmlDTO);
            log.info("回复内容:"+reply);
            //TODO 放装成方法传入接收到的语句查询数据库找到回复语句返回
//            if ("我是谁".equals(Content)){
//                textMessage.setContent("您好，你是"+ FromUserName+"吗？");
//            }
            //发送方法
            String sendMessage = weixinService.sendMessage(reply);

            //加密回复消息
            encryptMsg = wxcpt.EncryptMsg(sendMessage, timestamp, nonce);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptMsg;
    }
}
